﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using ErikLieben.SharePoint.Generic;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;

namespace ErikLieben.SharePoint.WebParts
{
    [Guid("3e063b71-9e21-4a94-a0b7-2392b11ea654")]
    public class BirthdayWatchWebPart : BaseWebPart
    {
        #region [ Constructor ]
        public BirthdayWatchWebPart() { }
        #endregion

        #region [ Fields ]

        private DataList lstEmployeesList;

        #endregion

        #region [ Overridden Methods ]
        protected override string DeterminateView()
        {
            return @"~/_controltemplates/FaceBookWebPart/BirthdayWatchWebPartControl.ascx";
        }

        protected override void WireUpControls()
        {
            if (FindControl<DataList>("lstEmployeesList", out lstEmployeesList, true))
                FillDataListWithUserData(lstEmployeesList);
        }

        protected override void WireUpSharePointControls(Control uiTemplate)
        {
        }
        #endregion

        #region [ Private Methods ]
        private void FillDataListWithUserData(BaseDataList list)
        {
            List<FaceBookUser> users = new List<FaceBookUser>();
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                Range<DateTime> dateRange = new Range<DateTime>(DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0)), DateTime.Now.AddDays(5));

                UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);
                foreach (UserProfile profile in profileManager)
                {
                    DateTime compareDate = Parse<DateTime>(profile["Birthday"]);
                    if (Parse<Boolean>(profile["VisibleInFaceBook"]) &&
                        dateRange.Contains(new DateTime(DateTime.Now.Year, compareDate.Month, compareDate.Day)))

                        users.Add(new FaceBookUser()
                        {
                            Name = Parse<String>(profile["PreferredName"]),
                            Photo = Parse<String>(profile["PictureURL"]),
                            MySiteUrl = Parse<String>(profile["PersonalSpace"]),
                            HireDate = Parse<DateTime>(profile["SPS-HireDate"]),
                            BirthDay = Parse<DateTime>(profile["Birthday"])
                        });
                }
            }

            users.Sort(delegate(FaceBookUser user1, FaceBookUser user2)
            {
                DateTime birtday1 = new DateTime(DateTime.Now.Year, user1.BirthDay.Month, user1.BirthDay.Day);
                DateTime birtday2 = new DateTime(DateTime.Now.Year, user2.BirthDay.Month, user2.BirthDay.Day);
                return birtday1.CompareTo(birtday2);
            });

            lstEmployeesList.DataSource = users;
            lstEmployeesList.DataBind();
        }

        private static T Parse<T>(UserProfileValueCollection valueCollection) where T : IConvertible
        {
            if (valueCollection == null || valueCollection.Value == null) return default(T);

            try
            {
                return (T)Convert.ChangeType(valueCollection.Value, typeof(T));
            }
            catch (Exception) { }

            return default(T);
        }

        #endregion
    }
}
